package com.library;

import java.io.IOException;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Address;
import com.liferay.portal.service.AddressLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.slayer.model.LMSBook;
import com.slayer.service.LMSBookLocalServiceUtil;

/**
 * Portlet implementation class LibraryPortlet
 */

public class LibraryPortlet extends MVCPortlet {

	public void updateBook(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {

		String bookTitle = ParamUtil.getString(actionRequest, "bookTitle");
		String author = ParamUtil.getString(actionRequest, "author");

		long bookId = ParamUtil.getLong(actionRequest, "bookId");
		
		LMSBook lmsBook = LMSBookLocalServiceUtil.insertBook(bookId, bookTitle, author, actionResponse);
		saveAddress(actionRequest, lmsBook);
	}
	
	public void deleteBook(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {

		long bookId = ParamUtil.getLong(actionRequest, "bookId");
		String redirectURL = ParamUtil.getString(actionRequest, "redirectURL");
		
		if (bookId > 0l) { // valid bookId
			try {
				LMSBookLocalServiceUtil.deleteLMSBook(bookId);
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (SystemException e) {
				e.printStackTrace();
			}
		}
		actionResponse.sendRedirect(redirectURL);
	}
	
	@Override
	public void render(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {

		setSortParams(request);
		super.render(request, response);
	}

	private void setSortParams(RenderRequest request) {
		String jspPage = ParamUtil.getString(request, "jspPage");

		if (jspPage.equalsIgnoreCase(LibraryConstants.PAGE_LIST)) {
			String orderByCol = ParamUtil.getString(request, "orderByCol", "bookTitle");
			request.setAttribute("orderByCol", orderByCol);

			String orderByType = ParamUtil.getString(request, "orderByType", "asc");
			request.setAttribute("orderByType", orderByType);
		}
	}

	public void searchBooks(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {

		String searchTerm = ParamUtil.getString(actionRequest, "searchTerm");

		if (Validator.isNotNull(searchTerm)) {
			try {
				List<LMSBook> lmsBooks = LMSBookLocalServiceUtil.searchBooks(searchTerm);

				actionRequest.setAttribute("SEARCH_RESULT", lmsBooks);
				actionResponse.setRenderParameter("jspPage",LibraryConstants.PAGE_LIST);

			} catch (SystemException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void deleteBooks(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {

		String bookIdsForDelete = ParamUtil.getString(actionRequest, "bookIdsForDelete");

		bookIdsForDelete = "[" + bookIdsForDelete + "]";
		bookIdsForDelete = bookIdsForDelete.replaceAll(":", "-");

		JSONArray jsonArray = null;
		try {
			jsonArray = JSONFactoryUtil.createJSONArray(bookIdsForDelete);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		if (Validator.isNotNull(jsonArray)) {
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);

				long bookId = jsonObject.getLong("bookId");
				try {
					LMSBookLocalServiceUtil.deleteLMSBook(bookId);
				} catch (PortalException e) {
					e.printStackTrace();
				} catch (SystemException e) {
					e.printStackTrace();
				}
			}
		}

		actionResponse.setRenderParameter("jspPage", LibraryConstants.PAGE_LIST);
	}
	
	private void saveAddress(ActionRequest actionRequest, LMSBook lmsBook) {
		
		boolean saveAddress = ParamUtil.getBoolean(actionRequest, "saveAddress", false);
		if (!saveAddress)
			return;
		long addressId = ParamUtil.getLong(actionRequest, "addressId");
		long countryId = ParamUtil.getLong(actionRequest, "countryId");
		long regionId = ParamUtil.getLong(actionRequest, "regionId");
		int typeId = ParamUtil.getInteger(actionRequest, "type");
		long userId = PortalUtil.getUserId(actionRequest);
		
		String city = ParamUtil.getString(actionRequest, "city");
		String street1 = ParamUtil.getString(actionRequest, "street1");
		String street2 = ParamUtil.getString(actionRequest, "street2");
		String zip = ParamUtil.getString(actionRequest, "zip");

		ServiceContext serviceContext = new ServiceContext();
		
		if(addressId <= 0) {
			try {
				AddressLocalServiceUtil.addAddress(
						userId, LMSBook.class.getName(), lmsBook.getPrimaryKey(), 
						street1, street2, StringPool.BLANK, city, zip, regionId, countryId, typeId, 
						true, true, serviceContext);
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (SystemException e) {
				e.printStackTrace();
			}
		} else {
			updateAddress(addressId, typeId, countryId, city, street1, street2, zip, userId);
		}
	}
	
	private void updateAddress(long addressId,int typeId, long countryId, String city,
			String street1, String street2, String zip, long userId) {

		Address address = null;
		try {
			address = AddressLocalServiceUtil.getAddress(addressId);
		} catch (PortalException e1) {
			e1.printStackTrace();
		} catch (SystemException e1) {
			e1.printStackTrace();
		}

		address.setCountryId(countryId);
		address.setCity(city);
		address.setStreet1(street1);
		address.setStreet2(street2);
		address.setZip(zip);

		address.setUserId(userId);

		address.setTypeId(typeId);
		address.setPrimary(true);

		try {
			AddressLocalServiceUtil.updateAddress(address);
		} catch (SystemException e) {
			e.printStackTrace();
		}
	}
}